<?php

namespace App\Services\ClientUser;

use App\Dto\ClientDto;
use App\Enums\JwtUserTypeEnum;
use App\Models\Client\ClientUserModel;
use App\Models\Wechat\WechatUserModel;
use App\Services\BaseService;
use App\Services\ServiceTrait;
use Illuminate\Database\Eloquent\Builder;

class ClientUserService extends BaseService
{
    use ServiceTrait;
    public function filter(): void
    {
        $this->query
            ->when($queryValue = $this->getParam('agent_id'), function (Builder $q) use ($queryValue) {
                $q->where('agent_id', $queryValue);
            })
            //昵称
            ->when($queryValue = $this->getParam('nickname'), function (Builder $q) use ($queryValue) {
                $q->where('nickname', 'like', '%' . $queryValue . '%');
            })
            //手机号
            ->when($queryValue = $this->getParam('mobile'), function (Builder $q) use ($queryValue) {
                $q->where('mobile', $queryValue);
            })
            //创建时间
            ->when($queryValue = $this->getParam('created_time'), function (Builder $q) use ($queryValue) {
                $q->whereBetween('created_at', get_date_range($queryValue));
            });
    }

    public function login()
    {
        $client = ClientUserModel::query()->create([
            'nickname' => '测试用户' . time(),
            'mobile' => '13800138000',
            'agent_id' => 1,
        ]);
        return $this->getJwtToken($client);
    }

    /**
     * 详情
     * @return mixed
     */
    public function info(): mixed
    {
        $static = ClientUserModel::query()
            ->where([
                'id' => ClientDto::userId()
            ])
            ->firstOrFail();
        return $static;
    }

    /**
     * 列表
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function lists(): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $this->setQuery(
            ClientUserModel::query()
                ->with([
                    'referrerUser' => function ($q) {
                        $q->withTrashed();
                        $q->select('id', 'agent_id', 'referrer', 'nickname', 'avatar');
                    }
                ])
        );

        return $this->paginate();
    }

    /**
     * 更新用户信息
     * @return array
     */
    public function update(): array
    {
        $user = ClientDto::getUser();
        $user->nickname = $this->getParam('nickname');
        $updateData = [
            'nickname' => $this->getParam('nickname'),
        ];
        if ($mobile = $this->getParam('mobile')) {
            // $user->mobile = $mobile;
            // $updateData['mobile'] = $mobile;
        }
        $user->save();
        WechatUserModel::query()->where('id', '=', $user->wechat_user_id)->update($updateData);
        return [];
    }

    /**
     * 退出登录
     * @return array
     */
    public function logout(): array
    {
        auth('client')->logout();
        return [];
    }

    /**
     * 开发版本登录
     * @return array
     */
    public function devLogin()
    {
        $clientUser = ClientUserModel::query()->find($this->getParam('client_user_id'));
        return $this->getJwtToken($clientUser);
    }

    /**
     * 获取jwt
     * @param $clientUser
     * @return array
     */
    public function getJwtToken($clientUser): array
    {
        //下发鉴权的jwt
        $payload = [
            'agent_id' => $clientUser->agent_id,
            'client_user_id' => $clientUser->id,
        ];
        $jwt = auth(JwtUserTypeEnum::CLIENT_USER)->claims($payload)->login($clientUser);
        $expiresIn = auth(JwtUserTypeEnum::CLIENT_USER)->factory()->getTTL() * 60;
        return [
            'token' => $jwt,
            'token_type' => 'bearer',
            'expires_in' => $expiresIn,
        ];
    }
}
